package com.jcbase.controller.wechat;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;

import com.alibaba.fastjson.JSON;
import com.jcbase.core.BaseConstance;
import com.jcbase.core.auth.interceptor.AuthorityInterceptor;
import com.jcbase.core.auth.interceptor.SysLogInterceptor;
import com.jcbase.core.util.CommonUtils;
import com.jcbase.core.util.RedisExt;
import com.jcbase.core.weixin.interceptor.ApiInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.NotAction;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.kit.SignatureCheckKit;

/**
 * @category 微信消息
 * 
 * @author yiz
 * @date 2016年8月3日 下午4:35:26
 * @version 1.0.0 
 * @copyright 
 */
@Before(ApiInterceptor.class)
@Clear({ AuthorityInterceptor.class, SysLogInterceptor.class })
public class WechatMsgController extends Controller {
	private static final Logger logger = LoggerFactory.getLogger(WechatMsgController.class);
	//	private String inMsgXml = null; // 本次请求 xml数据
	//	private InMsg inMsg = null; // 本次请求 xml 解析后的 InMsg 对象
	private final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

	public void index() {
		String signature = getPara("signature");
		String echostr = getPara("echostr");
		String nonce = getPara("nonce");
		String timestamp = getPara("timestamp");
		if (!checkSignature(signature, timestamp, nonce)) {
			logger.error("签名校验失败signature={},timestamp={}，nonce={}", signature, timestamp, nonce);
			return;
		}
		if (CommonUtils.isNotEmpty(echostr)) {
			renderText(echostr);
			return;
		} else {
			//			String content = null;
			//			InMsg msg = getInMsg();
			//			String content = getInMsgXml();
			//			logger.info("请求的参数....");
			//			if (msg instanceof InTextMsg)
			//				content = JSON.toJSONString((InTextMsg) msg);
			//			else if (msg instanceof InImageMsg)
			//				content = JSON.toJSONString((InImageMsg) msg);
			//			else if (msg instanceof InVoiceMsg)
			//				content = JSON.toJSONString((InVoiceMsg) msg);
			//			else if (msg instanceof InVideoMsg)
			//				content = JSON.toJSONString((InVideoMsg) msg);
			//			else if (msg instanceof InShortVideoMsg) //支持小视频
			//				content = JSON.toJSONString((InShortVideoMsg) msg);
			//			else if (msg instanceof InLocationMsg)
			//				content = JSON.toJSONString((InLocationMsg) msg);
			//			else if (msg instanceof InLinkMsg)
			//				content = JSON.toJSONString((InLinkMsg) msg);
			//			else if (msg instanceof InCustomEvent)
			//				content = JSON.toJSONString((InCustomEvent) msg);
			//			else if (msg instanceof InFollowEvent)
			//				content = JSON.toJSONString((InFollowEvent) msg);
			//			else if (msg instanceof InQrCodeEvent)
			//				content = JSON.toJSONString((InQrCodeEvent) msg);
			//			else if (msg instanceof InLocationEvent)
			//				content = JSON.toJSONString((InLocationEvent) msg);
			//			else if (msg instanceof InMassEvent)
			//				content = JSON.toJSONString((InMassEvent) msg);
			//			else if (msg instanceof InMenuEvent)
			//				content = JSON.toJSONString((InMenuEvent) msg);
			//			else if (msg instanceof InSpeechRecognitionResults)
			//				content = JSON.toJSONString((InSpeechRecognitionResults) msg);
			//			else if (msg instanceof InTemplateMsgEvent)
			//				content = JSON.toJSONString((InTemplateMsgEvent) msg);
			//			else if (msg instanceof InShakearoundUserShakeEvent)
			//				content = JSON.toJSONString((InShakearoundUserShakeEvent) msg);
			//			else if (msg instanceof InVerifySuccessEvent)
			//				content = JSON.toJSONString((InVerifySuccessEvent) msg);
			//			else if (msg instanceof InVerifyFailEvent)
			//				content = JSON.toJSONString((InVerifyFailEvent) msg);
			//			else if (msg instanceof InPoiCheckNotifyEvent)
			//				content = JSON.toJSONString((InPoiCheckNotifyEvent) msg);
			String content = null;
			try {
				content = JSON.toJSONString(parseRequestXML(getRequest().getInputStream()));
				logger.info("微信消息内容content={}", content);
				//推送至redis队列
				RedisExt.lpush(BaseConstance.WX_RESPONSE, content);
			} catch (Exception e) {
				logger.error("转换xml异常e={}", e);
			}
			renderText("");
		}
	}

	@Before(NotAction.class)
	public Map<String, String> parseRequestXML(InputStream is) throws Exception {
		Map<String, String> data = new HashMap<String, String>();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(is);
		Element root = doc.getDocumentElement();
		for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) {
			if (!(node instanceof Element)) {
				continue;
			}
			Element child = (Element) node;
			Node contentNode = child.getFirstChild();
			if (contentNode instanceof Text) {
				Text text = (Text) contentNode;
				data.put(child.getNodeName(), text.getTextContent());
			}
		}
		return data;
	}

	/**
	 * 检测签名
	 */
	private boolean checkSignature(String signature, String timestamp, String nonce) {
		if (StrKit.isBlank(signature) || StrKit.isBlank(timestamp) || StrKit.isBlank(nonce)) {
			return false;
		}
		if (SignatureCheckKit.me.checkSignature(signature, timestamp, nonce)) {
			return true;
		} else {

			return false;
		}
	}

	/*private InMsg getInMsg() {
		if (inMsg == null)
			inMsg = InMsgParser.parse(getInMsgXml());
		return inMsg;
	}
	
	private String getInMsgXml() {
		if (inMsgXml == null) {
			inMsgXml = HttpKit.readData(getRequest());
	
			// 是否需要解密消息
			if (ApiConfigKit.getApiConfig().isEncryptMessage()) {
				inMsgXml = MsgEncryptKit.decrypt(inMsgXml, getPara("timestamp"), getPara("nonce"),
						getPara("msg_signature"));
			}
		}
		logger.info("inMsgXml={}", inMsgXml);
		return inMsgXml;
	}*/
}
